package setting

import (
	"log"
	"time"
	"io/ioutil"
	"gopkg.in/yaml.v2"
)

var (
	Config *ConfigStruct
	RunMode string
	HTTPPort int
	ReadTimeout time.Duration
	WriteTimeout time.Duration
	PageSize int
	JwtSecret string
)

type ConfigStruct struct {
	Server   ServerConfig   `yaml:"server"`
	App      AppConfig      `yaml:"app"`
	Database DatabaseConfig `yaml:"database"`
	Redis    RedisConfig    `yaml:"redis"`
	Wechat   WechatConfig   `yaml:"wechat"`
}

type ServerConfig struct {
	RunMode      string `yaml:"run-mode"`
	HTTPPort     int    `yaml:"http-port"`
	ReadTimeout  int    `yaml:"read-timeout"`
	WriteTimeout int    `yaml:"write-timeout"`
}

type AppConfig struct {
	PageSize          int    `yaml:"page_size"`
	JwtSecret         string `yaml:"jwt_secret"`
	RuntimeRootPath   string `yaml:"runtime_root_path"`
	ImageSavePath     string `yaml:"image_save_path"`
	ImageMaxSize      int    `yaml:"image_max_size"`
	ImageAllowExts    string `yaml:"image_allow_exts"`
	ExportSavePath    string `yaml:"export_save_path"`
	QrCodeSavePath    string `yaml:"qr_code_save_path"`
	FontSavePath      string `yaml:"font_save_path"`
	LogSavePath       string `yaml:"log_save_path"`
	LogSaveName       string `yaml:"log_save_name"`
	LogFileExt        string `yaml:"log_file_ext"`
	TimeFormat        string `yaml:"time_format"`
}

type DatabaseConfig struct {
	Type       string `yaml:"type"`
	User       string `yaml:"user"`
	Password   string `yaml:"password"`
	Host       string `yaml:"host"`
	Name       string `yaml:"name"`
	TablePrefix string `yaml:"table_prefix"`
}

type RedisConfig struct {
	Host        string `yaml:"host"`
	Password    string `yaml:"password"`
	MaxIdle     int    `yaml:"max_idle"`
	MaxActive   int    `yaml:"max_active"`
	IdleTimeout int    `yaml:"idle_timeout"`
}

type WechatConfig struct {
	AppID         string `yaml:"app_id"`
	AppSecret     string `yaml:"app_secret"`
	Token         string `yaml:"token"`
	EncodingAESKey string `yaml:"encoding_aes_key"`
}

func init() {
	var err error
	// 读取YAML配置文件
	yamlFile, err := ioutil.ReadFile("conf/config.yml")
	if err != nil {
		log.Fatalf("Fail to read 'conf/config.yml': %v", err)
	}
	
	Config = &ConfigStruct{}
	err = yaml.Unmarshal(yamlFile, Config)
	if err != nil {
		log.Fatalf("Fail to parse 'conf/config.yml': %v", err)
	}
	
	LoadBase()
	LoadServer()
	LoadApp()
}

func LoadBase() {
	RunMode = Config.Server.RunMode
}

func LoadServer() {
	HTTPPort = Config.Server.HTTPPort
	ReadTimeout = time.Duration(Config.Server.ReadTimeout) * time.Second
	WriteTimeout = time.Duration(Config.Server.WriteTimeout) * time.Second
}

func LoadApp() {
	PageSize = Config.App.PageSize
	JwtSecret = Config.App.JwtSecret
}